# -*- coding: utf-8 -*-

# Copyright (c) 2025 Lijiang
# Licensed under the MIT License
# See LICENSE file for details

"""
力江视频压缩工具自动化构建脚本
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path
from config import (
    get_app_info, get_build_config, get_pyinstaller_config, 
    get_nsis_config, DEV_DEPENDENCIES, APP_NAME
)

class Builder:
    def __init__(self):
        self.project_root = Path(__file__).parent
        self.dist_dir = self.project_root / "dist"
        self.build_dir = self.project_root / "build"
        
    def clean_build(self):
        """清理之前的构建文件"""
        print("🧹 清理构建目录...")
        
        ############################### 清理构建输出目录 ###############################
        dirs_to_clean = [self.dist_dir, self.build_dir]
        for dir_path in dirs_to_clean:
            if dir_path.exists():
                try:
                    shutil.rmtree(dir_path)
                    print(f"  ✅ 删除目录: {dir_path.name}")
                except PermissionError:
                    print(f"  ⚠️  无法删除目录: {dir_path.name} (权限不足，跳过)")
                except Exception as e:
                    print(f"  ⚠️  删除目录失败: {dir_path.name} - {e}")
        
        ############################### 清理临时文件 ###############################
        temp_files = [
            "*.pyc",
            "*.pyo", 
            "*.pyd",
            "*.log"
        ]
        
        for pattern in temp_files:
            for file_path in self.project_root.rglob(pattern):
                try:
                    if file_path.is_file():
                        file_path.unlink()
                except PermissionError:
                    print(f"  ⚠️  无法删除文件: {file_path.name} (权限不足，跳过)")
                except Exception as e:
                    print(f"  ⚠️  删除文件失败: {file_path.name} - {e}")
        
        ############################### 清理__pycache__目录 ###############################
        for pycache_dir in self.project_root.rglob("__pycache__"):
            try:
                shutil.rmtree(pycache_dir)
                print(f"  ✅ 删除缓存目录: {pycache_dir.relative_to(self.project_root)}")
            except PermissionError:
                print(f"  ⚠️  无法删除缓存目录: {pycache_dir.relative_to(self.project_root)} (权限不足，跳过)")
            except Exception as e:
                print(f"  ⚠️  删除缓存目录失败: {pycache_dir.relative_to(self.project_root)} - {e}")
        
        print("✅ 清理完成")
        return True
    
    def check_icon(self):
        """检查图标文件是否存在"""
        icon_path = self.project_root / "icon.ico"
        if icon_path.exists():
            print(f"✅ 找到图标文件: {icon_path}")
            return True
        else:
            print(f"⚠️  未找到图标文件: {icon_path}")
            print("💡 请将您的图标文件命名为 'icon.ico' 并放在项目根目录")
            print("   如果没有图标文件，将使用默认图标")
            return True  # 不强制要求图标文件
    
    def install_dependencies(self):
        """安装构建依赖"""
        print("📦 安装构建依赖...")
        
        for dep in DEV_DEPENDENCIES:
            try:
                subprocess.run([sys.executable, "-m", "pip", "install", dep], check=True)
                print(f"   ✅ {dep}")
            except subprocess.CalledProcessError as e:
                print(f"   ❌ {dep} 安装失败: {e}")
                return False
        
        print("✅ 依赖安装完成")
        return True
    
    def build_executable(self):
        """使用PyInstaller构建可执行文件"""
        print("🔨 构建可执行文件...")
        
        pyinstaller_config = get_pyinstaller_config()
        spec_file = self.project_root / pyinstaller_config['spec_file']
        if not spec_file.exists():
            print(f"❌ PyInstaller spec文件不存在: {spec_file}")
            return False
        
        try:
            cmd = [
                sys.executable, "-m", "PyInstaller",
                "--clean",
                "--noconfirm", 
                str(spec_file)
            ]
            
            subprocess.run(cmd, check=True, cwd=self.project_root)
            print("✅ 可执行文件构建完成")
            return True
            
        except subprocess.CalledProcessError as e:
            print(f"❌ 构建失败: {e}")
            return False
    
    def create_installer(self):
        """创建安装包"""
        print("📦 创建安装包...")
        
        ############################### 查找NSIS安装路径 ###############################
        nsis_paths = [
            "makensis",  # 如果在PATH中
            r"D:\Program Files (x86)\NSIS\Bin\makensis.exe",  # D盘安装路径
            r"C:\Program Files (x86)\NSIS\Bin\makensis.exe",  # C盘安装路径
            r"C:\Program Files\NSIS\Bin\makensis.exe",  # 64位安装路径
        ]
        
        makensis_cmd = None
        for path in nsis_paths:
            try:
                if path == "makensis":
                    # 检查是否在PATH中
                    subprocess.run([path, "/VERSION"], check=True, capture_output=True)
                else:
                    # 检查具体路径
                    if os.path.exists(path):
                        subprocess.run([path, "/VERSION"], check=True, capture_output=True)
                makensis_cmd = path
                print(f"✅ 找到NSIS: {path}")
                break
            except (subprocess.CalledProcessError, FileNotFoundError):
                continue
        
        if not makensis_cmd:
            print("❌ NSIS未安装或不在PATH中")
            print("   请从 https://nsis.sourceforge.io/ 下载并安装NSIS")
            print("   或者将NSIS添加到系统PATH环境变量中")
            return False
        
        nsis_config = get_nsis_config()
        nsi_file = self.project_root / nsis_config['script_file']
        if not nsi_file.exists():
            print(f"❌ NSIS脚本文件不存在: {nsi_file}")
            return False
        
        try:
            cmd = [makensis_cmd, str(nsi_file)]
            subprocess.run(cmd, check=True, cwd=self.project_root)
            print("✅ 安装包创建完成")
            return True
            
        except subprocess.CalledProcessError as e:
            print(f"❌ 安装包创建失败: {e}")
            return False
    
    def build(self):
        """执行完整构建流程"""
        app_info = get_app_info()
        print(f"🚀 开始构建{app_info['name']}...")
        print("=" * 50)
        
        steps = [
            ("清理构建目录", self.clean_build),
            ("检查图标文件", self.check_icon),
            ("安装构建依赖", self.install_dependencies),
            ("构建可执行文件", self.build_executable),
            ("创建安装包", self.create_installer),
        ]
        
        for step_name, step_func in steps:
            print(f"\n📋 {step_name}")
            print("-" * 30)
            
            if not step_func():
                print(f"\n❌ 构建失败: {step_name}")
                return False
        
        print("\n" + "=" * 50)
        print("🎉 构建完成！")
        print(f"📁 可执行文件位置: {self.dist_dir}")
        print("📦 安装包已创建在项目根目录")
        
        return True

def main():
    """主函数"""
    builder = Builder()
    
    if len(sys.argv) > 1 and sys.argv[1] == "--clean":
        builder.clean_build()
        return
    
    success = builder.build()
    sys.exit(0 if success else 1)

if __name__ == "__main__":
    main()
